package com.imooc.rabbitmq.exchange.direct;

import com.imooc.rabbitmq.utils.ConnectionUtils;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class DirectConsumer {
    private static final String exchangeName = "test_direct_exchange";
    private static final String exchangeType = "direct";
    private static final String routingKey = "test.direct";
    private static final String queueName = "test_direct_queue";

    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = ConnectionUtils.getConnection();

        //2. 通过Connection 创建一个channel
        Channel channel = connection.createChannel();

        //3.声明一个交换机   durable：是否持久化
        channel.exchangeDeclare(exchangeName,exchangeType,true,false,false,null);
        //生命一个队列
        channel.queueDeclare(queueName,false,false,false,null);
        //建立一个绑定关系
        channel.queueBind(queueName,exchangeName,routingKey);

        DefaultConsumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String msg = new String(body,"utf-8");
                System.out.println("recv:"+msg);
            }
        };
        //监听队列
        channel.basicConsume(queueName,true, consumer);
    }

}
